#include "Api7841.h"
#include "simCanFunc.h"

static int g_Handle[4];

typedef struct CfgInf
{
	int carNum;
	int portNum;
}CAN_CONFIG_INF;

CAN_CONFIG_INF g_CanCfgInf[4] = {{0,0},{0,1},{1,0},{1,1}};

void InitializeCan(void)
{
	int i;
	
	for(i = 0; i < 4;i++)
	{
		if ((g_Handle[i] = CanOpenDriver(g_CanCfgInf[i].carNum, g_CanCfgInf[i].portNum)) == -1)
		{
			printf("!!!Open Can Car %d port %d failed\n",g_CanCfgInf[i].carNum,g_CanCfgInf[i].portNum);
			return -1;
		}
		else
		{
			printf("CanOpen success!\n");
		}
	}
}

void OpenCanFuncImplement(_CanMessage_t *message)
{
	int index = 0;
	
	index = message->carNum * 2 + message->portNum;
	
	ConfigCanPort(g_Handle[index],2);
	
	return;
}

void CloseCanFuncImplement(_CanMessage_t *message)
{
	int index = 0;
	
	index = message->carNum * 2 + message->portNum;
	
	CanCloseDriver(g_Handle[index]);
	
	return;
}

void WriteCanFuncImplement(_CanMessage_t *message)
{
	int index = 0;
	int iRetVal = 0;
	CAN_PACKET sndPacket;
	
	index = message->carNum * 2 + message->portNum;
	
	CanClearTxBuffer(g_Handle[index]);

	sndPacket.rtr = 0;
	sndPacket.len = message->buffLength;
	sndPacket.canId = message->messageId;

	memcpy(sndPacket.data,message->buff,message->buffLength);
	
	iRetVal = CanSendMsg(g_Handle[index], &sndPacket);
	if (iRetVal == -1)
	{
		printf("CAN Message send failed\n");
	}
}

void ReadCanFuncImplement(_CanMessage_t *message)
{
	int i;
	int index = 0;
	int iRetVal = 0;
	int iRecvCnt = 0;
	unsigned char *buff;
	CAN_PACKET recvPacket;
	
	index = message->carNum * 2 + message->portNum;
	CanClearRxBuffer(g_Handle[index]);
	iRecvCnt = CanGetRcvCnt(g_Handle[index]);
	buff = (unsigned char *)malloc(iRecvCnt* 12);
	
	for(i = 0; i < iRecvCnt;i++)
	{
		if((iRetVal = CanRcvMsg(g_Handle[index], &recvPacket))!= -1)
		{
			memcpy(buff+3*i*4 ,&recvPacket.canId,sizeof(long));
			memcpy(buff+(3*i+1)*4 ,&recvPacket.data,8);
		}
	}	
	
	memcpy(message->buff,buff, iRecvCnt*12);
	message->messageCnt = iRecvCnt;
	message->buffLength = iRecvCnt*12;
	
	free(buff);	
}


void ReleaseCan(void)
{
	return;
}
